package com.lengxf.mybatis.generate;

import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class ColumnGenerate {

    private final static List<String> IGNORE_COLUMN_LIST = List.of(
            "id",
            "update_time", "update_by", "create_time", "create_by", "updated_user",
            "created_user");


    public static String generate(TableInfo tableInfo) {
        String columnName = tableInfo.getColumnName();
        String columnType = tableInfo.getColumnType();
        String comment = tableInfo.getTableComment();
        ColumnType type = ColumnType.getType(columnName, columnType);
        String column = processColumnName(columnName);
        if (column == null) {
            return null;
        }
        String newComment = StringUtils.isNotBlank(comment) ? comment : columnName;
        return "`" + column + "`" + " " + type.getType() + " " +
                "DEFAULT" + " " + type.getDefaultValue() + " "
                + "COMMENT" + " '" + newComment + "'";
    }

    private static String processColumnName(String columnName) {
        int lasted = columnName.lastIndexOf("_");
        if (lasted < 0) {
            return columnName.toLowerCase();
        }
        if (columnName.endsWith("_S") || columnName.endsWith("_I")
                || columnName.endsWith("_B") || columnName.endsWith("F")
                || columnName.endsWith("_T") || columnName.equals("_Y")) {
            String lowerCase = columnName.substring(0, lasted).toLowerCase();
            if (IGNORE_COLUMN_LIST.contains(lowerCase)) {
                return null;
            }
            return lowerCase;
        }
        return columnName.toLowerCase();
    }


}
